<template>
  <div class="restaurant-list">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="餐厅名称">
          <el-input v-model="searchForm.name" placeholder="请输入餐厅名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增餐厅</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="name" label="餐厅名称" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="businessHours" label="营业时间" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '营业中' : '已关闭' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="餐厅图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              class="table-image"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleStatus(row)">
              {{ row.status === 1 ? '关闭营业' : '开始营业' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="餐厅名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入餐厅名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-time-picker
            v-model="formData.openTime"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            :picker-options="{
              format: 'HH:mm'
            }"
            style="width: 130px"
          />
          <span class="mx-2">至</span>
          <el-time-picker
            v-model="formData.closeTime"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            :picker-options="{
              format: 'HH:mm'
            }"
            style="width: 130px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">营业中</el-radio>
            <el-radio :label="0">已关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
        <el-form-item label="餐厅图片" prop="image">
          <el-upload
            class="restaurant-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
          >
            <img v-if="formData.image" :src="formData.image" class="restaurant-image">
            <el-icon v-else class="restaurant-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getRestaurantPage, saveRestaurant, updateRestaurant, deleteRestaurant, updateRestaurantStatus } from '@/api/restaurant.js'
import { uploadImage } from '@/api/upload'
import { formatTime } from '@/utils/format'

// 搜索表单
const searchForm = ref({
  name: ''
})

// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await getRestaurantPage({
      pageNum: page.value.current,
      pageSize: page.value.size,
      name: searchForm.value.name
    })
    tableData.value = res.data.records
    page.value.total = res.data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value.current = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.value.name = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  page.value.size = val
  getList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  page.value.current = val
  getList()
}

// 编辑弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const formData = ref({
  id: '',
  name: '',
  address: '',
  phone: '',
  openTime: '',
  closeTime: '',
  status: 1,
  description: '',
  image: ''
})

// 表单校验规则
const formRules = {
  name: [{ required: true, message: '请输入餐厅名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  openTime: [{ required: true, message: '请选择开始营业时间', trigger: 'change' }],
  closeTime: [{ required: true, message: '请选择结束营业时间', trigger: 'change' }]
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增餐厅'
  dialogVisible.value = true
  formData.value = {
    id: '',
    name: '',
    address: '',
    phone: '',
    openTime: '',
    closeTime: '',
    status: 1,
    description: '',
    image: ''
  }
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑餐厅'
  dialogVisible.value = true
  formData.value = { ...row }
  // 解析营业时间
  if (row.businessHours) {
    const [openTime, closeTime] = row.businessHours.split('-')
    formData.value.openTime = openTime
    formData.value.closeTime = closeTime
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该餐厅吗?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRestaurant(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 修改状态
const handleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const tipText = newStatus === 1 ? '开始营业' : '关闭营业'

  ElMessageBox.confirm(`确认${tipText}吗?`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await updateRestaurantStatus(row.id, newStatus)
      ElMessage.success('操作成功')
      getList()
    } catch (error) {
      console.error('操作失败:', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (formData.value.id) {
      await updateRestaurant({
        ...formData.value,
        businessHours: `${formData.value.openTime}-${formData.value.closeTime}`
      })
      ElMessage.success('更新成功')
    } else {
      await saveRestaurant({
        ...formData.value,
        businessHours: `${formData.value.openTime}-${formData.value.closeTime}`
      })
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.value = {
    id: '',
    name: '',
    address: '',
    phone: '',
    openTime: '',
    closeTime: '',
    status: 1,
    description: '',
    image: ''
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传
const handleUpload = async (params) => {
  try {
    const res = await uploadImage(params.file)
    formData.value.image = res.data
    ElMessage.success('上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.restaurant-list {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.restaurant-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.restaurant-uploader:hover {
  border-color: #409EFF;
}

.restaurant-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.restaurant-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.table-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.mx-2 {
  margin: 0 10px;
}
</style>

